import { combineReducers } from 'redux';
import { 
  ADD_TODO, DEL_TODO, COMPLETE_TODO,CHANGE_TEXT,
  EDIT_TODO, GET_EDIT_CONTENT, GET_EDIT_INDEX,
  CLEAR_EDIT_CONTENT
} from './actions';

function todos(state = [], action) {
  switch (action.type) {
    case ADD_TODO:
      return [...state, Object.assign({}, state, {
        text: action.value,
        completed: action.completed
      })];
    case DEL_TODO:
      return [
        ...state.slice(0, action.index),
        ...state.slice(action.index+1)
      ];
    case COMPLETE_TODO:
      return [
        ...state.slice(0, action.index),
        Object.assign({}, state[action.index], {
          completed: !action.completed
        }),
        ...state.slice(action.index+1)
      ];
    case EDIT_TODO:
      return [
        ...state.slice(0, action.index),
        Object.assign({}, state[action.index], {
          text: action.value
        }),
        ...state.slice(action.index+1)
      ]
    default:
      return state;
  }
}

// 获取输入框的值
function inputValue(state = '', action) {
  switch (action.type) {
    case CHANGE_TEXT:
      return action.text;
    case GET_EDIT_CONTENT:
      return action.value;
    case CLEAR_EDIT_CONTENT:
      return state = '';
    default:
      return state;
  }
}

// 获取编辑目标序号
function editIndex(state = null, action) {
  switch (action.type) {
    case GET_EDIT_INDEX:
      return action.index;
    case CLEAR_EDIT_CONTENT:
      return state = null;
    default:
      return state;
  }
}

export default combineReducers({
  todos,
  inputValue,
  editIndex
});
